﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeml.Document.Contracts;
using Xeml.Document;
using Mpi.Common.Collections;
using System.Diagnostics;

namespace XemlCore.Indexing
{
    public sealed class ObservationIndexer
    {
        #region Singleton pattern
        static readonly ObservationIndexer instance = null;

        static ObservationIndexer()
        {
            instance = new ObservationIndexer();
        }

        ObservationIndexer()
        {
        }

        public static ObservationIndexer Instance
        {
            get { return instance; }
        }
        #endregion

        private IDocument doc;
        private int _count = short.MinValue;

        public void Init(IDocument doc)
        {
            if (this.doc != doc)
            {
                this.doc = doc;
                System.Threading.Interlocked.Exchange(ref _count, FindCurrentIndex());
            }
        }

        public short NextId()
        {
            return Convert.ToInt16(System.Threading.Interlocked.Increment(ref _count));
        }

        private int FindCurrentIndex()
        {
            int res = short.MinValue;
            foreach (TreeNode<StoryBase> node in doc.StoryBoard.VirtualRoot.SubNodes(true))
            {
                foreach (ObservationPoint op in node.Content.ObservationPoints)
                {
                    foreach (Observation o in op.Observations)
                    {
                        res = Math.Max(o.Id, res);
                    }
                }
            }
            return res;
        }
    }
}
